using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Xml.Serialization;
using System.IO;

/// <summary>
/// Summary description for Users
/// </summary>
public class Users
{
	public class User
	{
		public string Username;
		public string Password;
		public string HomeDir;
	}

	[XmlArray("Users")]
	[XmlArrayItem("User", typeof(Users.User))]
	public ArrayList UserList;

	[XmlIgnore]
	public Page Page;

	public Users()
	{
		UserList = new ArrayList();
	}

	public Users(Page page)
	{
		UserList = new ArrayList();
		Page = page;
	}

	public bool Login(string username, string password)
	{
		for (int i = 0; i < UserList.Count; i++)
		{
			if (((User)UserList[i]).Username == username &&
				((User)UserList[i]).Password == password)
			{
				Page.Session.Clear();
				Page.Session.Add("Username", username);
				return true;
			}
		}

		return false;
	}

	public Users.User GetUser(string username)
	{
		for (int i = 0; i < UserList.Count; i++)
		{
			if (((User)UserList[i]).Username == username)
				return ((User)UserList[i]);
		}

		return null;
	}

	public void Save()
	{
		XmlSerializer s = new XmlSerializer(typeof(Users));
		TextWriter w = new StreamWriter(Page.Application["PHYSICAL_BASE_PATH"] + "App_Data/Users.xml");
		s.Serialize(w, this);
		w.Close();
	}

	public static Users Load(Page page)
	{
		Users users = new Users();

		if (File.Exists(page.Application["PHYSICAL_BASE_PATH"] + "App_Data/Users.xml"))
		{
			XmlSerializer s = new XmlSerializer(typeof(Users));
			TextReader r = new StreamReader(page.Application["PHYSICAL_BASE_PATH"] + "App_Data/Users.xml");
			users = (Users)s.Deserialize(r);
			r.Close();
		}
		else
			throw new FileNotFoundException("The file could not be found", page.Application["PHYSICAL_BASE_PATH"] + "App_Data/Users.xml");

		users.Page = page;
		return users;
	}
}
